﻿@using SmartStore.Web.Framework.UI;
@using SmartStore.Web.Framework.UI.Choices;

@model ChoiceModel
@{ 
	var storeUrl = EngineContext.Current.Resolve<IWebHelper>().GetStoreLocation(false);
	var controlId = Model.BuildControlId();
	var disabled = Model.IsDisabled;	// TODO?
	var clientId = "upload" + CommonHelper.GenerateRandomInteger();
	var containerId = clientId + "container";

	//ex. ['jpg', 'jpeg', 'png', 'gif'] or []
	var allowedFileExtensions = string.Join("|", Model.AllowedFileExtensions.Select(x => x.Trim()).ToList());
}

<div id="@containerId">
	<input id="@(controlId)" name="@(controlId)" type="hidden" class="hidden" />

	@(Html.SmartStore().FileUploader()
		.Name(clientId)
		.UploadUrl(Model.GetFileUploadUrl(Url))
		.AcceptedFileTypes(allowedFileExtensions)
		.ShowRemoveButton(Model.UploadedFileGuid.HasValue())
		.ShowRemoveButtonAfterUpload(true)
		.UploadText(T("Common.FileUploader.Upload"))
		.OnUploadCompletedHandlerName("onFileUploaded" + clientId)
		.OnFileRemoveHandlerName("onFileRemoved" + clientId)
	)

	<div class="uploaded-file mt-2 hide"></div>
</div>

<script type="text/javascript">
	window['onFileUploaded@(clientId)'] = function (e, el, data) {
		var result = data.result;

		if (result.downloadGuid) {
			setUploadedFile(result.downloadGuid, data.files[0].name, "@(containerId)");
		}

		if (result.message) {
			displayNotification(result.message, "success");
		}
	};

	window['onFileRemoved@(clientId)'] = function (e, el) {
		$('#@containerId .hidden').val('');
		$('#@containerId .uploaded-file').empty().hide();
    }

    function setUploadedFile(downloadGuid, fileName, containerId) {
        if (!_.isEmpty(downloadGuid) && downloadGuid !== '0') {
            $('#' + containerId + ' .hidden').val(downloadGuid);

        	var downloadLink = "@storeUrl" + "download/getfileupload/?downloadId=" + downloadGuid;
        	var fileLink = '<a href="' + downloadLink + '" class="fileuploadattribute" rel="nofollow">' + fileName + '</a>';

            $('#' + containerId + ' .uploaded-file').html(fileLink).show();
        }
    }

    $(function () {
        setUploadedFile('@Model.UploadedFileGuid', '@Model.UploadedFileName');
    });
</script>